package com.corner.ui.activity;

import android.app.Dialog;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.corner.R;
import com.corner.app.App;
import com.corner.app.GlobalParams;
import com.corner.presenter.base.BasePresenter;
import com.corner.ui.base.BaseActivity;
import com.corner.utils.AppManager;
import com.corner.utils.BitmapUtil;
import com.corner.utils.DialogUtil;
import com.corner.utils.DownLoadUtil;
import com.corner.utils.FileUtil;
import com.corner.utils.ToastUtil;
import com.corner.utils.view.CustomImageView;
import com.corner.utils.view.FindView;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * Created by Administrator on 2015/5/6.
 */
public class ShowImageActivity extends BaseActivity implements View.OnClickListener, PhotoViewAttacher.OnViewTapListener {
    public static final String IMAGE_URL = "imageUrl";
    public static final String IMAGE_PATH = "imagePath";
    @FindView(R.id.view_custom_image_view)
    private CustomImageView customImageView;//

    @FindView(R.id.tv_show_pic_save)
    private TextView tvSave;
    @FindView(R.id.fl_progress_show_pic)
    private RelativeLayout frameLayout;
    private String imageUrl;
    private String imagePath;
    private String path;
    private Dialog saveDialog;
    private TextView tvEnsure;
    private TextView tvCancel;
    private PhotoViewAttacher attacher;

    @Override
    protected BasePresenter createP() {
        return null;
    }

    @Override
    protected void setOnClick() {
        tvSave.setOnClickListener(this);
        frameLayout.setOnClickListener(this);
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        attacher = new PhotoViewAttacher(customImageView);
        attacher.setOnViewTapListener(this);
        customImageView.setAttacher(attacher);
        path = GlobalParams.APPFIEPATH + "/" + "saveImage/";
        imagePath = getIntent().getStringExtra(IMAGE_PATH);
        Uri uri = null;
        if (!TextUtils.isEmpty(imagePath)) {
            uri = Uri.parse("file://" + imagePath);
        } else {
            imageUrl = getIntent().getStringExtra(IMAGE_URL);
            if (!TextUtils.isEmpty(imageUrl)) {
                uri = Uri.parse(imageUrl);
            }
        }
        customImageView.setImageUri(uri, new CustomImageView.OnGetBitmapCallback() {
            @Override
            public void onGetBitmap() {
                frameLayout.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void initView() {
        super.initView();
    }

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_show_pic);
    }

    @Override
    protected void onResume() {
        overridePendingTransition(R.anim.shwo_pic_in_bottom, R.anim.anim_none);
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_show_pic_save:
                showSaveImageDialog();
                break;
            case R.id.fl_progress_show_pic:
                AppManager.getInstance().finishActivity(this);
                overridePendingTransition(R.anim.anim_none, R.anim.show_image_out_bottom);
                break;
            case R.id.tv_save_image_cancel:
                DialogUtil.hideDialog(saveDialog);
                break;
            case R.id.tv_save_image_ensure:
                DialogUtil.hideDialog(saveDialog);
                if (!TextUtils.isEmpty(imagePath)) {
                    ToastUtil.showCustomToastInRelease(ShowImageActivity.this, StringUtils.replace(getString(R.string.image_save), getString(R.string.image_save_search), imagePath));
                } else {
                    if(customImageView.getBitmap()!=null){
                        saveBitmap();
                    }else {
                        downloadAndSaveBitmap();
                    }
                }
                break;
        }
    }

    /**
     * 下载并保存bitmap
     */
    private void downloadAndSaveBitmap() {
        DownLoadUtil.getInstance().getFilePath(path + System.currentTimeMillis() + ".jpg", imageUrl, new DownLoadUtil.GetFileCallBack() {
            @Override
            public void onFinish(String filePath) {
                hideProgressDialog();
                if (filePath != null) {
                    ToastUtil.showCustomToastInRelease(ShowImageActivity.this, StringUtils.replace(getString(R.string.image_save), getString(R.string.image_save_search), path));
                } else {
                    ToastUtil.showCustomToastInRelease(ShowImageActivity.this, getString(R.string.image_save_failed));
                }
            }
        });
        showProgressDialog();
    }

    private void saveBitmap() {
        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                imagePath = path + imageUrl.hashCode()+".jpg";
                try {
                    FileUtil.write2SDCard(new File(imagePath), customImageView.getBitmap());
                    subscriber.onNext(null);
                } catch (IOException e) {
                    subscriber.onError(new Throwable("文件处理异常"));
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Object>() {
                    @Override
                    public void call(Object o) {
                        ToastUtil.showCustomToastInRelease(ShowImageActivity.this, StringUtils.replace(getString(R.string.image_save), getString(R.string.image_save_search), imagePath));
                        hideProgressDialog();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        ToastUtil.showCustomToastInRelease(App.application, throwable.getMessage());
                        hideProgressDialog();
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        customImageView.onDestroy();
    }

    private void showSaveImageDialog() {
        if (saveDialog == null) {
            saveDialog = DialogUtil.showDiaLog(R.layout.dialog_save_image, this);
            tvCancel = (TextView) saveDialog.findViewById(R.id.tv_save_image_cancel);
            tvEnsure = (TextView) saveDialog.findViewById(R.id.tv_save_image_ensure);
            tvCancel.setOnClickListener(this);
            tvEnsure.setOnClickListener(this);
        } else {
            saveDialog.show();
        }
    }


    @Override
    public void onViewTap(View view, float v, float v1) {
        AppManager.getInstance().finishActivity(this);
        overridePendingTransition(R.anim.anim_none, R.anim.show_image_out_bottom);
    }
}
